package com.example.community.controller.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.community.annotation.AccessLimit;
import com.example.community.util.CommunityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class SessionInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断请求是否是属于方法的请求
        if (handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod) handler;
            //获取方法上的注解，看是否有该注解
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if (null == accessLimit){
                return true;
            }
            int seconds = accessLimit.seconds();
            int maxCount = accessLimit.maxCount();
            //得到访问者的ip地址
            String ip = request.getRemoteAddr();
            //存放在redis中的key
            String key = request.getServletPath() + ":" + ip;
            Integer count = (Integer) redisTemplate.opsForValue().get(key);
            System.out.println(count);
            if (null == count || -1 == count) {
                // 第一次访问,设置过期时间
                redisTemplate.opsForValue().set(key, 1,seconds, TimeUnit.SECONDS);
                return true;
            }
            if (count < maxCount) {
                // count加1
                count = count + 1;
                //redisTemplate.opsForValue().set(key,count,0);
                redisTemplate.opsForValue().increment(key);
                return true;
            }
            // 超出访问次数
            if (count >= maxCount) {
                String xRequestedWith = request.getHeader("x-requested-with");
                if ("XMLHttpRequest".equals(xRequestedWith)) {
                    response.setContentType("application/plain;charset=utf-8");
                    PrintWriter writer = response.getWriter();
                    writer.write(CommunityUtil.getJSONString(233, "你操作太频繁了!"));
                    return false;
                }
            }

        }
        return true;
    }
}
